package com.bjsj.pro.ui;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.PermissionRequest;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alipay.sdk.app.PayTask;
import com.bjsj.pro.TourismApp;
import com.bjsj.pro.base.AAAPresentr;
import com.bjsj.pro.base.DemoActivity;
import com.bjsj.pro.base.HttpBean;
import com.bjsj.pro.base.MVPBaseActivity;
import com.bjsj.pro.base.MyBaseMvpView;
import com.bjsj.pro.base.NullView;
import com.bjsj.pro.base.RetJsonBean;
import com.bjsj.pro.bean.JavaScriptMetod;
import com.bjsj.pro.bean.LoginBean;
import com.bjsj.pro.bean.VersoinBean;
import com.bjsj.pro.bean.up_img_2Bean;
import com.bjsj.pro.bean.upmp3Bean;
import com.bjsj.pro.interfaces.OnJavaScriptMetodCallBack;
import com.bjsj.pro.tools.Configs;
import com.bjsj.pro.tools.Dialogutils;
import com.bjsj.pro.tools.FileUtil;
import com.bjsj.pro.tools.ImagerPickerUtils;
import com.bjsj.pro.tools.IntentTools;
import com.bjsj.pro.tools.MyOkgoUtils;
import com.bjsj.pro.tools.PermissionUtil;
import com.bjsj.pro.tools.PermissionUtils;
import com.bjsj.pro.tools.RecordUtils;
import com.bjsj.pro.tools.SeverUrl;
import com.bjsj.pro.tools.UpdateHelper;
import com.bjsj.pro.tools.getPhotoFromPhotoAlbum;
import com.bjsj.pro.view.PrimaryDialog;
import com.bjsj.pro.view.X5WebView;
import com.bjsj.pro.R;
import com.bjsj.pro.view.dialogflm.BaseDialog;
import com.bjsj.pro.wxapi.WXLoginCode;
import com.bjsj.pro.wxapi.WxPayData;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.okgo.model.HttpParams;
import com.nanchen.compresshelper.CompressHelper;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.Map;

import javax.xml.transform.Result;

import butterknife.BindView;
import cafe.adriel.androidaudioconverter.AndroidAudioConverter;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Created by Nevermore on 2018/1/20.
 * <p>
 * 轮播图商品详情
 */

public class BannderDetailsActivity extends MVPBaseActivity<NullView, AAAPresentr> implements
        NullView
{

    @BindView(R.id.webBannder)
    X5WebView webBannder;
    private String title;
    private String url;
    private String h5Title;
    private int maxImageNum = 1;
    private String upH5Image;
    private IWXAPI mIWXAPI;
    private int up_img_type;
    private boolean isLogin=false;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    private final int GET_TICKET= 100;//获取ticket
    private final int COPY_TEXT=101;//复制文字
    private final int ISLOGIN=102;//是否登录
    private final int GET_USERINFO=103;//获取用户信息
    private final int CALL_PHONE=104;//拨打电话
    private final int CHANGE_TITLE=105;//设置标题
    private final int FILE_DOWLOAD=106;//下载
    private final int IMG_UP=107;//上传
    private final int OPEN_XIANGCE=108;//打开相册
    private final int UP_H5_IMAGE=109;//上传h5
    private final int STRAT_RECORD=110;//上传h5
    private final int STOP_RECORD=111;//上传h5
    private final int CLOSE_RECORD=112;//上传h5


    //申请录音权限
    private static final int GET_RECODE_AUDIO = 1;
    private static String[] PERMISSION_AUDIO = {
            Manifest.permission.RECORD_AUDIO, // Speaker accessory
            Manifest.permission.CAMERA
    };
    private  RecordUtils recordUtils ;
    private boolean isShow;
    private float yzhow;
    private boolean isStart;
    private boolean isSend;
    private String mid;
    private int second;
    private String token="";
    /**
      * xbs_getTicket  获取ticket
      *      login_ticketback  ticket回调 @params ticket 字符串
      * isLogin   是否登录
      *      login_callback  登录回调 @params isLogin 是否登录 1 or 0
      * xbs_joinLogin  打开登录页面
      * xbs_getUserInfoRequest 获取用户信息
      *       xbs_getUserInfoCallback 用户信息回调 @param {userInfo}
      * xbs_closeWebView  关闭窗口
      * xbs_goBack  返回上一页
      * xbs_changeTitle  设置标题 @params {title}
      * xbs_seeBigPhoto  查看图片 @params {imageArr,index}
      * xbs_copyUrl    复制文字 @params {urlStr}
      * xbs_callPhone   打电话 @param {mobile}
      * xbs_uploadPhoto  上传图片 @params {allowsEdit}
      *      photo_callback 上传回调 @param url 成功的图片路径
      */
    @Override
    protected AAAPresentr createPresenter()
    {
        return new AAAPresentr(this);
    }

    private TextView tvtest;
    @Override
    protected int setLayoutResId()
    {
        return R.layout.activity_bannder_details;
    }
    private WebChromeClient mWebChromeClient = new WebChromeClient(){
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            tools.showToast(base,message);
            result.confirm();
            return true;
        }

        @Override
        public void onPermissionRequest(PermissionRequest request) {
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
                request.grant(request.getResources());
                request.getOrigin();
            }
        }
    };
    @Override
    protected void initData()
    {
        title = getIntent().getStringExtra("title");
        url = getIntent().getStringExtra("url");
        tvtest=(TextView)findViewById(R.id.tv_test);
        if(url==null){
            url="https://www1.hnbjsj.com/";
        }
        showTitleBarLayout(true,"博江小帮手",null,R.drawable.round_login);
        mIWXAPI = WXAPIFactory.createWXAPI(base, Configs.WX_APP_ID, true);
        mIWXAPI.registerApp(Configs.WX_APP_ID);
        EventBus.getDefault().register(this);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int mDensity = metrics.densityDpi;
        if (mDensity == 240) {
            webBannder.setZoom(WebSettings.ZoomDensity.FAR);
        } else if (mDensity == 160) {
            webBannder.setZoom(WebSettings.ZoomDensity.MEDIUM);
        } else if (mDensity == 120) {
            webBannder.setZoom(WebSettings.ZoomDensity.CLOSE);
        } else if (mDensity == DisplayMetrics.DENSITY_XHIGH) {
            webBannder.setZoom(WebSettings.ZoomDensity.FAR);
        } else if (mDensity == DisplayMetrics.DENSITY_TV) {
            webBannder.setZoom(WebSettings.ZoomDensity.FAR);
        }
        webBannder.getSettings().setJavaScriptEnabled(true);
        webBannder.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webBannder.requestFocus();
        //FileUtil.createVoiceDir();
        LoginBean userInfo = getUserInfo();
        if(userInfo!=null)
        {
            isLogin=true;
            final CloudPushService pushService = PushServiceFactory.getCloudPushService();
            pushService.bindAccount(userInfo.getData().getUid(), null);
            token=userInfo.getData().getToken();
        }
      //  PermissionUtil.applyxfPermissions(this);
        checkNotifySetting();
       // verifyAudioPermissions(base);
        getversoin();
        Object isys=tools.readObject(base,Configs.SAVE_ISYS_KEY, Configs.SAVE_ISYS_NAME);
        if(isys==null){
            tools.showPrimaryDialog(base, new PrimaryDialog.PrimaryDialogListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    TourismApp.initdata();
                }
            });
        }
        //FileUtil.createVoiceDir();

    }

    @Override
    protected void initView()
    {
        Log.d("ffffffffff",url);
        webBannder.loadUrl(url);
        webBannder.addJavascriptInterface(new JavaScriptMetod(new OnJavaScriptMetodCallBack() {
            @Override
            public void xbs_callPhone(String phone) {//打电话
                try {
                    JSONObject json = new JSONObject(phone);
                    String moblie = json.optString("mobile");
                  //  baseHandler.sendEmptyMessageAtTime(GO_USER_PHONE, 1000);
                    Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
                    startActivity(dialIntent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void xbs_copyUrl(String urlStr) {//复制
                JSONObject json = null;
                try {
                    json = new JSONObject(urlStr);
                    String shareUrlH5 = json.getString("urlStr");
                    if (!TextUtils.isEmpty(shareUrlH5)) {
                        copyString(shareUrlH5);
                    } else {
                        tools.showToast(base, "复制失败,链接内容不存在!");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void xbs_getTicket() {//获取token
                checkPermission();
                //微信登录
                if (!mIWXAPI.isWXAppInstalled()) {
                    tools.showToast(base, "您还未安装微信客户端");
                    return;
                }
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_login";
                mIWXAPI.sendReq(req);

            }

            @Override
            public void xbs_getUserInfoRequest() {//获取用户信息

            }

            @Override
            public void xbs_changeTitle(String title) {//修改标题
                try {
                    JSONObject json = new JSONObject(title);
                    h5Title = json.optString("title");
                    baseHandler.sendEmptyMessageAtTime(CHANGE_TITLE, 1000);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void xbs_uploadPhoto(String allowsEditjson) {
                /*Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent,1);*/
                Log.d("ssssssssss",allowsEditjson);
                JSONObject json = null;
                try {
                    json = new JSONObject(allowsEditjson);
                    int allowsEdit = json.optInt("allowsEdit", 0);
                    up_img_type=json.optInt("type",0);
                    if (allowsEdit == 1) {
                        ImagerPickerUtils.initImagePickerSingle(true);
                    } else {
                        ImagerPickerUtils.initImagePickerSingle(false);
                    }
                    baseHandler.sendEmptyMessageAtTime(OPEN_XIANGCE, 1000);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void xbs_logout() {
                final CloudPushService pushService = PushServiceFactory.getCloudPushService();
                pushService.unbindAccount(null);
                tools.saveObject(base, Configs.SAVE_LOGIN_KEY, Configs.SAVE_LOGIN_SP_NAME, null);
                tools.showToast(base,"退出登陆");
            }

            @Override
            public void xbs_orderPay(String apppayrequest) {
                Log.d("ffffffffffff",apppayrequest+"");
               // Dialogutils.paycloudquickpay(base,apppayrequest);
                JSONObject json = null;
                try {
                    json = new JSONObject(apppayrequest);
                    /*this.appid=appid;
                    this.noncestr=noncestr;
                    this.packages=packages;
                    this.partnerid=partnerid;
                    this.prepayid=prepayid;
                    this.sign=sign;
                    this.timestamp=timestamp;*/
                    int pay_type = json.optInt("pay_type");
                    switch (pay_type){
                        case 2:
                            String appid=json.optString("appid");
                            String nonceStr=json.optString("noncestr");
                            String packages=json.optString("package");
                            String timeStamp=json.optString("timestamp");
                            String paySign=json.optString("paySign");
                            String prepay_id=json.optString("prepayid");
                            String partnerid=json.optString("partnerid");
                            WxPayData wxPayData=new WxPayData(appid,nonceStr,packages,partnerid,prepay_id,paySign,timeStamp);
                            Dialogutils.startWxPay(base,wxPayData);
                            break;
                        case 3:
                            String alipay_res=json.optString("alipay_res");
                            startzfb(alipay_res );
                            break;
                        case 4:
                            Dialogutils.payAlipaymini(BannderDetailsActivity.this,apppayrequest);
                            break;
                        case 5:
                            Dialogutils.payWx(BannderDetailsActivity.this,apppayrequest);
                            break;
                    }
                    /*if(pay_type==4){
                        Dialogutils.payAlipaymini(BannderDetailsActivity.this,apppayrequest);
                    }else {
                        Dialogutils.payWx(BannderDetailsActivity.this,apppayrequest);
                    }*/
                    /*Intent i4 = new Intent(getApplication(), PushTzActivity.class);
                    i4.putExtra("url", url);
                    i4.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                    startActivity(i4);*/
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void xbs_startRecord() {
                Log.d("wwwwwwwwwwwww","录音");
                baseHandler.sendEmptyMessageAtTime(STRAT_RECORD, 1000);

            }
            @Override
            public void xbs_closeRecord() {
                Log.d("wwwwwwwwwwwww","关闭");
              //  recordUtils.stopRecord();
                baseHandler.sendEmptyMessageAtTime(CLOSE_RECORD, 1000);

            }
            @Override
            public void xbs_stopRecord(String data) {
                JSONObject json = null;
                try {
                    json = new JSONObject(data);
                    mid= json.optString("mid");
                    second=json.optInt("second",0);
                    token=json.optString("token");
                    baseHandler.sendEmptyMessageAtTime(STOP_RECORD, 1000);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                /*recordUtils.stopRecord();
                //发送语音
                recordUtils.setOnTranscodingListener(new RecordUtils.OnTranscodingListener() {
                    @Override
                    public void complete(String path, int duration) {
                        Log.d("uuuuuu",path);
                        File videofile=new File(path);
                        webBannder.loadUrl("javascript: xbs_stopRecordCallback(\'"+videofile+"\')");
                       *//* if (isSend) {
                            sendVoiceFile(path, duration);
                        } else {
                            //事后删除录音
                            new File(path).delete();
                        }*//*

                    }
                });*/
               Log.d("wwwwwwwwwwwww","停止");

            }

        }),"Android");


        webBannder.setWebChromeClient(mWebChromeClient);

        //长按录音


    }



    private static long exitTime = 0;

    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast toast = Toast.makeText(base, "再按一次退出！", Toast.LENGTH_SHORT);
            toast.show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) ) {
            if (webBannder.canGoBack())
            {
                webBannder.goBack(); //goBack()表示返回WebView的上一页面
                return true;
            }else
            {
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    Toast toast = Toast.makeText(base, "再按一次退出！", Toast.LENGTH_SHORT);
                    toast.show();
                    exitTime = System.currentTimeMillis();
                } else {
                    finish();
                    System.exit(0);
                    return true;
                }

            }

        }
        return false;
    }


    @Subscribe(threadMode = ThreadMode.MainThread)
    public void messageEventBus(WXLoginCode event) {
        tools.logD("===========messageEventBus event：" + event.getRespCode());
        if (event.getGetType().equals("303774") && !TextUtils.isEmpty(event.getRespCode())) {
            //微信登陆成功后返回code,然后通过code去获取用户个人资料
           // getWXUserInfo(base, event.getRespCode());
            startLogin(event.getRespCode());
        } else {
            tools.showToast(base, "获取微信授权信息失败!");
        }

    }


    private void copyString(String copyString) {
        if (!TextUtils.isEmpty(copyString)) {
            ClipboardManager clipboardManager = (ClipboardManager) base.getSystemService(Context.CLIPBOARD_SERVICE);
            clipboardManager.setPrimaryClip(ClipData.newPlainText(null, copyString));
            tools.showToast(base, "复制成功!");
        }
    }


    public void handlerMessage(Message msg)
    {
       // super.handlerMessage(msg);
        switch (msg.what)
        {
            case CALL_PHONE:
                tools.showToast(base, "成功");
                break;
            case COPY_TEXT:
                tools.showToast(base, "app复制成功");
                break;
            case CHANGE_TITLE:
                if (!TextUtils.isEmpty(h5Title)) {
                    mTitleBarLayout.setTitle(h5Title.toString().trim());
                }
                break;
            case OPEN_XIANGCE:
                if(up_img_type==1){
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    startActivityForResult(intent,1);
                }else {
                    //打开相册
                    if (!XXPermissions.hasPermission(base, Permission.Group.STORAGE)) {
                        PermissionUtils.getSDtorPermisstion(base, new PermissionUtils.Permissions() {
                            @Override
                            public void getPermission(boolean isAll) {
                                if (isAll) {
//                              所有获取权限成功
                                    IntentTools.gotoPick(base, maxImageNum);
                                } else {
//                  获取权限成功，部分权限未正常授予
                                }
                            }
                        });
                    } else {
                        IntentTools.gotoPick(base, maxImageNum);
                    }
                }
                break;
            case UP_H5_IMAGE:
                //照片传给h5
                Log.d("sssssssssssss",upH5Image);
                //webBannder.loadUrl("javascript: photo_callback(\""+upH5Image+"\")");
                webBannder.loadUrl("javascript: photo_callback(\'"+upH5Image+"\')");
                break;
            case STRAT_RECORD:
              /*  recordUtils = RecordUtils.getInstance(base);
                recordUtils.startRecordnew();*/
                if (!isShow) {
                    recordUtils = RecordUtils.getInstance(base);
                   // dialog = DialogUtils.showAudioDialog((AppCompatActivity) getActivity());
                    isShow = true;
                   // yzhow = motionEvent.getY();
                    isStart = true;
                 //   btnAudio.setText("松开结束");
                 //   btnAudio.setBackgroundResource(R.drawable.shape_gray_press);
                    recordUtils.startRecord();
                    Log.d("wwwwwwww","qweqwe");
                }
                break;
            case STOP_RECORD:
               // recordUtils.stopRecordnew();
                recordUtils.stopRecord();
                isSend = false;
                if (isShow) {
                   // if ((yzhow - 100) <= motionEvent.getY()) {
                        isSend = true;
                  //  }
                    //发送语音
                    recordUtils.setOnTranscodingListener(new RecordUtils.OnTranscodingListener() {
                        @Override
                        public void complete(String path, int duration) {
                            if (isSend) {
                                Log.d("kkkkkkkk",path);
                               // Toast.makeText(base,path,Toast.LENGTH_SHORT).show();
                               /* File videofile=new File(path);
                                String s="sadasd";
                                webBannder.loadUrl("javascript: xbs_stopRecordCallback(\'"+s+"\')");
                                Toast.makeText(base,path,Toast.LENGTH_SHORT).show();
                                Log.d("kkkkkkkk",path);*/
                                // sendVoiceFile(path, duration);
                                upmp3(path);
                            } else {
                                //事后删除录音
                                new File(path).delete();
                            }
                        }
                    });
                    isShow = false;
                }
                break;
            case CLOSE_RECORD:
                recordUtils.stopRecord();
                isSend = false;
                if (isShow) {
                    // if ((yzhow - 100) <= motionEvent.getY()) {
                    isSend = true;
                    //  }
                    //发送语音
                    recordUtils.setOnTranscodingListener(new RecordUtils.OnTranscodingListener() {
                        @Override
                        public void complete(String path, int duration) {
                            if (isSend) {
                                Log.d("kkkkkkkk",path);
                            } else {
                                //事后删除录音
                                new File(path).delete();
                            }
                        }
                    });
                    isShow = false;
                }
                break;
        }
    }

    ArrayList<ImageItem> images = null;
    String path;
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {

            Uri uri = data.getData();

            if ("file".equalsIgnoreCase(uri.getScheme())){//使用第三方应用打开

                path = uri.getPath();

                //tv.setText(path);

                Toast.makeText(this,path+"11111",Toast.LENGTH_SHORT).show();

                return;

            }

            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后

                path = getPath(this, uri);

             //   tv.setText(path);

                Toast.makeText(this,path,Toast.LENGTH_SHORT).show();

            }

        }

        if (requestCode == Configs.REQUEST_ALBUM_OK) {

            String photoPath = getPhotoFromPhotoAlbum.getRealPathFromUri(this, data.getData());
          //  uploadImage(photoPath);
            tools.logD("=======相册:" + photoPath);
        }


        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == Configs.REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    //  adapter.setImages(selImageList);
                 //   tools.logD("==========selImageList" + picList.size());
                    tools.logD("==========images" + images.size());
                    // picList.clear();
                    for (int i = 0; i < images.size(); i++) {
                        if(up_img_type==1) {
                            uploadImage(images.get(i).path);
                        }else {
                            uploadImage_2(images.get(i).path);
                        }
                  /*      picList.add(images.get(i).path);
                        mImageUrlrAdapter.setImages(picList);*/
                    }

                }
            } else if (data != null && requestCode == Configs.REQUEST_CODE_PHONE) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                  //  tools.logD("==========REQUEST_CODE_SELECT selImageList" + picList.size());
                    tools.logD("==========REQUEST_CODE_SELECT images" + images.size());
                    // adapter.setImages(selImageList);
                    for (int i = 0; i < images.size(); i++) {
                        if(up_img_type==1){
                            uploadImage(images.get(i).path);
                        }else {
                            uploadImage_2(images.get(i).path);
                        }

                        //  picList.add(images.get(i).path);
                        //   mImageUrlrAdapter.setImages(picList);
                    }
                }
            }

        }
    }


    public void uploadImage(String path) {
        File newFile = CompressHelper.getDefault(base)
                .compressToFile(new File(path));

        HttpBean mHttpBean = new HttpBean(getSupportFragmentManager());
        mHttpBean.setHttpGetType(Configs.OKGO_POST);
        mHttpBean.setHttpurl(SeverUrl.IMG_UP);
        mHttpBean.setGetType(Configs.OKGO_GET_TYPE_PROGRESS);
        HttpParams params = new HttpParams();
        params.put("file", newFile);
        params.put("isApp",1);
        mHttpBean.setToken(getToken());
        mHttpBean.setHttpParams(params);
        MyOkgoUtils.newInstance().startHttpRequest(base, mHttpBean, up_img_2Bean.class, new MyBaseMvpView<up_img_2Bean>() {
            @Override
            public void onSuccessShowData(up_img_2Bean data) {
                super.onSuccessShowData(data);
                Gson gson=new Gson();
                String json=gson.toJson(data);
                if (!TextUtils.isEmpty(data.getData().getTurl())) {
                    upH5Image = json;
                    baseHandler.sendEmptyMessageAtTime(UP_H5_IMAGE, 1000);
                }

            }

        });

    }


    public void upmp3(String path) {
        File newFile = new File(path);
        HttpBean mHttpBean = new HttpBean(getSupportFragmentManager());
        mHttpBean.setHttpGetType(Configs.OKGO_POST);
        mHttpBean.setHttpurl(SeverUrl.UP_MP3);
        mHttpBean.setGetType(Configs.OKGO_GET_TYPE_PROGRESS);
        HttpParams params = new HttpParams();
        params.put("file", newFile);
        params.put("isApp",1);
        mHttpBean.setToken(token);
        mHttpBean.setHttpParams(params);
        MyOkgoUtils.newInstance().startHttpRequest(base, mHttpBean, upmp3Bean.class, new MyBaseMvpView<upmp3Bean>() {
            @Override
            public void onSuccessShowData(upmp3Bean data) {
                super.onSuccessShowData(data);
             /*   Gson gson=new Gson();
                String json=gson.toJson(data);
                if (!TextUtils.isEmpty(data.getData().getTurl())) {
                    upH5Image = json;
                    baseHandler.sendEmptyMessageAtTime(UP_H5_IMAGE, 1000);
                }*/
               // webBannder.loadUrl("javascript: xbs_stopRecordCallback(\'"+data.getData().getFile()+"\')");
                Log.d("eeeeeeee","dsadasda");
                sendNotice(data.getData().getFile());
            }

        });

    }


    public void uploadImage_2(String path) {
        File newFile;
        if(up_img_type==1){
            newFile=new File(path);
        }else {
            newFile = CompressHelper.getDefault(base)
                    .compressToFile(new File(path));
        }
        HttpBean mHttpBean = new HttpBean(getSupportFragmentManager());
        mHttpBean.setHttpGetType(Configs.OKGO_POST);
        mHttpBean.setHttpurl(SeverUrl.IMG_UP_2);
        mHttpBean.setGetType(Configs.OKGO_GET_TYPE_PROGRESS);
        HttpParams params = new HttpParams();
        params.put("Filedata", newFile);
        params.put("name",newFile.getName());
        params.put("isApp",1);
        if(up_img_type==1){
            params.put("type","file");
        }
        else {
            params.put("type","atlas");
        }
        mHttpBean.setToken(getToken());
        mHttpBean.setHttpParams(params);
        MyOkgoUtils.newInstance().startHttpRequest(base, mHttpBean, up_img_2Bean.class, new MyBaseMvpView<up_img_2Bean>() {
            @Override
            public void onSuccessShowData(up_img_2Bean data) {
                super.onSuccessShowData(data);
                if(up_img_type==1){
                   // sendNotice();
                }else {
                    Gson gson = new Gson();
                    String json = gson.toJson(data);
                    if (!TextUtils.isEmpty(data.getData().getTurl())) {
                        upH5Image = json;
                        baseHandler.sendEmptyMessageAtTime(UP_H5_IMAGE, 1000);
                    }
                }


            }

        });

    }


    public void sendNotice(String path) {
        HttpParams params = new HttpParams();
        params.put("mid", mid);
        params.put("second",second);
        params.put("type",8);
        params.put("msg",path);
        params.put("isApp",1);
        params.put("token",token);
        HttpBean mHttp = new HttpBean(getSupportFragmentManager());
        mHttp.setHttpGetType(Configs.OKGO_GET);
        mHttp.setGetType(Configs.OKGO_GET_TYPE_PROGRESS);
        mHttp.setHttpurl(SeverUrl.SEND_NOTICE);//WX_LOGIN
        mHttp.setToken(token);
        mHttp.setHttpParams(params);

        MyOkgoUtils.newInstance().startHttpRequest(base, mHttp, LoginBean.class, new MyBaseMvpView<LoginBean>() {
            @Override
            public void onSuccessShowData(LoginBean data) {
                super.onSuccessShowData(data);

            }
        });
    }


    public void startLogin(String code) {
        HttpParams params = new HttpParams();
        params.put("code", code);
        params.put("isApp",1);
        /* params.put("unionid", mWXUserInfo.getUnionid());
        params.put("sex", mWXUserInfo.getSex());
        params.put("provice", mWXUserInfo.getProvince());
        params.put("city", mWXUserInfo.getCity());*/
        HttpBean mHttp = new HttpBean(getSupportFragmentManager());
        mHttp.setHttpGetType(Configs.OKGO_GET);
        mHttp.setGetType(Configs.OKGO_GET_TYPE_PROGRESS);
        mHttp.setHttpurl(SeverUrl.LOGIN);//WX_LOGIN
        mHttp.setHttpParams(params);

        MyOkgoUtils.newInstance().startHttpRequest(base, mHttp, LoginBean.class, new MyBaseMvpView<LoginBean>() {
            @Override
            public void onSuccessShowData(LoginBean data) {
                super.onSuccessShowData(data);
                Log.d("ccccccccccc",data.getData().getToken());
                token=data.getData().getToken();
                tools.saveObject(base, Configs.SAVE_LOGIN_KEY, Configs.SAVE_LOGIN_SP_NAME, data);
                final CloudPushService pushService = PushServiceFactory.getCloudPushService();
                pushService.bindAccount(data.getData().getUid(), null);
                setDevice();
                webBannder.loadUrl(data.getData().getToUrl());
            }
        });
    }


    public void setDevice() {

        HttpParams params = new HttpParams();
        params.put("system", "Android");
        params.put("versions",getLocalVersion(base));
        /* params.put("unionid", mWXUserInfo.getUnionid());
        params.put("sex", mWXUserInfo.getSex());
        params.put("provice", mWXUserInfo.getProvince());
        params.put("city", mWXUserInfo.getCity());*/
        HttpBean mHttp = new HttpBean(getSupportFragmentManager());
        mHttp.setHttpGetType(Configs.OKGO_GET);
        mHttp.setGetType(Configs.OKGO_GET_TYPE_PROGRESS);
        mHttp.setHttpurl(SeverUrl.LOGIN);//WX_LOGIN
        mHttp.setToken(getToken());
        mHttp.setHttpParams(params);

        MyOkgoUtils.newInstance().startHttpRequest(base, mHttp,RetJsonBean.class, new MyBaseMvpView<RetJsonBean>() {
            @Override
            public void onSuccessShowData(RetJsonBean data) {
                super.onSuccessShowData(data);

            }
        });
    }


    public void getversoin(){
        HttpBean mHttp = new HttpBean(getSupportFragmentManager());
        mHttp.setHttpGetType(Configs.OKGO_GET);
       // mHttp.setGetType(Configs.OKGO_GET_TYPE_PROGRESS);
        mHttp.setHttpurl(SeverUrl.GET_VERSION);//WX_LOGIN
        mHttp.setToken(getToken());
       // mHttp.setHttpParams(params);
        MyOkgoUtils.newInstance().startHttpRequest(base, mHttp, VersoinBean.class, new MyBaseMvpView<VersoinBean>() {
            @Override
            public void onSuccessShowData(final VersoinBean data) {
                super.onSuccessShowData(data);
                try {
                    String versoin=getVersionName();
                    if(data.getData().getLastVersion().compareTo(versoin)==1){
                        new AlertDialog.Builder(base).setTitle("更新提示")
                                                .setMessage(data.getData().getUpdateContent())
                                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface,int i) {

                                                    }
                                                })
                                                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {
                                                            UpdateHelper.autoInstallUpdate(base,data.getData().getDownloadUrl());
                                                    }
                                                }).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private String getVersionName() throws Exception
    {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
        String version = packInfo.versionName;
        return version;
    }


    public Boolean checkPermission() {
        boolean isGranted = false;
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                isGranted = false;
            }
            if (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) !=PackageManager.PERMISSION_GRANTED) {
                isGranted = false;
            }
            Log.i("读写权限获取"," ： "+isGranted);
            if (!isGranted) {
                this.requestPermissions(
                        new String[]{  Manifest.permission.VIBRATE, // Gimbal rotation
                                Manifest.permission.INTERNET, // API requests
                                Manifest.permission.ACCESS_WIFI_STATE, // WIFI connected products
                                Manifest.permission.ACCESS_COARSE_LOCATION, // Maps
                                Manifest.permission.ACCESS_NETWORK_STATE, // WIFI connected products
                                Manifest.permission.ACCESS_FINE_LOCATION, // Maps
                                Manifest.permission.CHANGE_WIFI_STATE, // Changing between WIFI and USB connection
                                Manifest.permission.WRITE_EXTERNAL_STORAGE, // Log files
                                Manifest.permission.BLUETOOTH, // Bluetooth connected products
                                Manifest.permission.BLUETOOTH_ADMIN, // Bluetooth connected products
                                Manifest.permission.READ_EXTERNAL_STORAGE, // Log files
                                Manifest.permission.READ_PHONE_STATE, // Device UUID accessed upon registration
                                //   Manifest.permission.SYSTEM_ALERT_WINDOW, // 悬浮窗
//            Manifest.permission.REQUEST_INSTALL_PACKAGES, // 安装未知应用
                                Manifest.permission.RECORD_AUDIO, // Speaker accessory
                                Manifest.permission.CAMERA
                              },
                        102);
            }
        }
        return isGranted;
    }

    /*
     * 申请录音权限*/
    public static void verifyAudioPermissions(Activity activity) {
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.RECORD_AUDIO);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, PERMISSION_AUDIO,
                    GET_RECODE_AUDIO);
        }
    }



    public void startzfb(final String orderinfo){
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(BannderDetailsActivity.this);
                Map<String,String> result = alipay.payV2(orderinfo,true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            /*Result result = new Result((String) msg.obj);
            Toast.makeText(DemoActivity.this, result.getResult(),
                    Toast.LENGTH_LONG).show();*/
        };
    };


    private void checkNotifySetting() {
        NotificationManagerCompat manager = NotificationManagerCompat.from(this);
        // areNotificationsEnabled方法的有效性官方只最低支持到API 19，低于19的仍可调用此方法不过只会返回true，即默认为用户已经开启了通知。
        boolean isOpened = manager.areNotificationsEnabled();

        if (isOpened) {
        } else {
            new AlertDialog.Builder(base).setTitle("提示")
                    .setMessage("还没有开启通知权限，点击去开启")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface,int i) {

                        }
                    })
                    .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent intent = new Intent();
                            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", getPackageName(), null);
                            intent.setData(uri);
                            startActivity(intent);

                        }
                    }).show();
        }
    }






    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if (this.webBannder!= null) {
            webBannder.destroy();
        }
    }


    public String getPath(final Context context, final Uri uri) {


        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;


// DocumentProvider

        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

// ExternalStorageProvider

            if (isExternalStorageDocument(uri)) {

                final String docId = DocumentsContract.getDocumentId(uri);

                final String[] split = docId.split(":");

                final String type = split[0];


                if ("primary".equalsIgnoreCase(type)) {

                    return Environment.getExternalStorageDirectory() + "/" + split[1];

                }

            }

// DownloadsProvider

            else if (isDownloadsDocument(uri)) {


                final String id = DocumentsContract.getDocumentId(uri);

                final Uri contentUri = ContentUris.withAppendedId(

                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));


                return getDataColumn(context, contentUri, null, null);

            }

// MediaProvider

            else if (isMediaDocument(uri)) {

                final String docId = DocumentsContract.getDocumentId(uri);

                final String[] split = docId.split(":");

                final String type = split[0];


                Uri contentUri = null;

                if ("image".equals(type)) {

                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

                } else if ("video".equals(type)) {

                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;

                } else if ("audio".equals(type)) {

                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

                }


                final String selection = "_id=?";

                final String[] selectionArgs = new String[]{split[1]};


                return getDataColumn(context, contentUri, selection, selectionArgs);

            }

        }

// MediaStore (and general)

        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            return getDataColumn(context, uri, null, null);

        }

// File

        else if ("file".equalsIgnoreCase(uri.getScheme())) {

            return uri.getPath();

        }

        return null;

    }

    public String getDataColumn(Context context, Uri uri, String selection,

                                String[] selectionArgs) {


        Cursor cursor = null;

        final String column = "_data";

        final String[] projection = {column};


        try {

            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,

                    null);

            if (cursor != null && cursor.moveToFirst()) {

                final int column_index = cursor.getColumnIndexOrThrow(column);

                return cursor.getString(column_index);

            }

        } finally {

            if (cursor != null)

                cursor.close();

        }

        return null;

    }


    /**

     * @param uri The Uri to check.

     * @return Whether the Uri authority is ExternalStorageProvider.

     */

    public boolean isExternalStorageDocument(Uri uri) {

        return "com.android.externalstorage.documents".equals(uri.getAuthority());

    }


    /**

     * @param uri The Uri to check.

     * @return Whether the Uri authority is DownloadsProvider.

     */

    public boolean isDownloadsDocument(Uri uri) {

        return "com.android.providers.downloads.documents".equals(uri.getAuthority());

    }


    /**

     * @param uri The Uri to check.

     * @return Whether the Uri authority is MediaProvider.

     */

    public boolean isMediaDocument(Uri uri) {

        return "com.android.providers.media.documents".equals(uri.getAuthority());

    }


}
